package com.example.demo.config;

import io.shardingsphere.core.api.algorithm.sharding.RangeShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.standard.RangeShardingAlgorithm;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

/**
 * 范围分片算法类
 *
 * @author 510830970@qq.com
 */
public class OrderRangeShardingAlgorithm implements RangeShardingAlgorithm<Timestamp> {

    public OrderRangeShardingAlgorithm() {

    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Timestamp> rangeShardingValue) {
        try {
            return getMonthBetween(collection,rangeShardingValue.getValueRange().lowerEndpoint(), rangeShardingValue.getValueRange().upperEndpoint());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获得两个日期之间的所有月份
     *
     * @param minDate
     * @param maxDate
     * @return
     * @throws ParseException
     * @author 510830970@qq.com
     */
    private static List<String> getMonthBetween(Collection<String> collection,Timestamp minDate, Timestamp maxDate) throws ParseException {
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//格式化为年月
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        min.setTime(minDate);
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
        max.setTime(maxDate);
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        Calendar curr = min;
        while (curr.before(max)) {
            String table="t_order_"+sdf.format(curr.getTime());
            if(collection.contains(table)){
                result.add(table);
            }
            curr.add(Calendar.MONTH, 1);
        }
        return result;
    }
}
